package com.spider.admin.scaffold.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spider.admin.scaffold.service.SystemRoleResourceService;
import com.spider.admin.scaffold.service.SystemRoleService;
import com.spider.admin.scaffold.service.UserRoleService;
import com.spider.admin.scaffold.utils.DateUtils;
import com.spider.admin.scaffold.utils.PageUtils;
import com.spider.admin.scaffold.entity.dto.RoleResourceDTO;
import com.spider.admin.scaffold.entity.enums.DataDictionaryEnum;
import com.spider.admin.scaffold.entity.model.SystemRoleResource;
import com.spider.admin.scaffold.entity.model.SystemRole;
import com.spider.admin.scaffold.entity.model.User;
import com.spider.admin.scaffold.entity.model.UserRole;
import com.spider.admin.scaffold.entity.param.SystemRoleQueryParam;
import com.spider.admin.scaffold.exception.BusinessException;
import com.spider.admin.scaffold.exception.ExceptionDef;
import com.spider.admin.scaffold.mapper.SystemRoleMapper;
import com.spider.admin.scaffold.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xiong.bo
 * @version 1.0
 * @date 2020/11/21 9:50
 */

@Service("systemRoleService")
public class SystemRoleServiceImpl extends ServiceImpl<SystemRoleMapper, SystemRole> implements SystemRoleService {

    @Autowired
    private SystemRoleResourceService roleResourceService;
    @Autowired
    private UserRoleService userRoleService;

    @Lazy
    @Autowired
    private UserService userService;

    @Override
    public Page<SystemRole> selectPage(SystemRoleQueryParam queryParam) {
        LambdaQueryWrapper<SystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(queryParam.getRoleName()), SystemRole::getRoleName, queryParam.getRoleName());
        queryWrapper.like(StringUtils.hasText(queryParam.getRoleCode()), SystemRole::getRoleCode, queryParam.getRoleCode());
        queryWrapper.orderByDesc(SystemRole::getCreateTime);
        return this.baseMapper.selectPage(queryParam.buildPage(), queryWrapper);
    }

    @Override
    public Page<SystemRole> selectActivePage(SystemRoleQueryParam queryParam) {
        LambdaQueryWrapper<SystemRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemRole::getDataStatus, DataDictionaryEnum.ENABLE.getCode());
        queryWrapper.like(StringUtils.hasText(queryParam.getRoleName()), SystemRole::getRoleName, queryParam.getRoleName());
        queryWrapper.like(StringUtils.hasText(queryParam.getRoleCode()), SystemRole::getRoleCode, queryParam.getRoleCode());
        queryWrapper.orderByDesc(SystemRole::getCreateTime);
        return this.baseMapper.selectPage(queryParam.buildPage(), queryWrapper);
    }

    @Override
    public SystemRole findById(Long id) {
        return getSystemRoleById(id);
    }

    //查看详情
    private SystemRole getSystemRoleById(Long id) {
        SystemRole systemRole = this.baseMapper.selectById(id);
        if (systemRole == null) {
            throw new BusinessException(ExceptionDef.ERROR_DATA_NOT_EXIST);
        }
        return systemRole;
    }

    @Override
    public SystemRole saveRole(SystemRole role) {
        if (StringUtils.isEmpty(role.getRoleCode()) || StringUtils.isEmpty(role.getRoleName())) {
            throw new BusinessException(ExceptionDef.ERROR_COMMON_PARAM_NULL);
        }
        SystemRole systemRole = new SystemRole();
        systemRole.setRoleCode(role.getRoleCode());
        systemRole.setRoleName(role.getRoleName());
        systemRole.setRemark(role.getRemark());
        int s = DataDictionaryEnum.ENABLE.getCode().equals(role.getDataStatus()) ? DataDictionaryEnum.ENABLE.getCode()
                : DataDictionaryEnum.DISABLE.getCode();
        systemRole.setDataStatus(s);
        this.baseMapper.insert(systemRole);

        return systemRole;
    }

    @Override
    public SystemRole updateRole(SystemRole role) {
        SystemRole existRole = getSystemRoleById(role.getId());
        existRole.setRoleName(!StringUtils.hasText(role.getRoleName()) ? existRole.getRoleName() : role.getRoleName());
        existRole.setRemark(!StringUtils.hasText(role.getRemark()) ? existRole.getRemark() : role.getRemark());
        int s = DataDictionaryEnum.ENABLE.getCode().equals(role.getDataStatus()) ? DataDictionaryEnum.ENABLE.getCode()
                : DataDictionaryEnum.DISABLE.getCode();
        existRole.setDataStatus(s);
        this.baseMapper.updateById(existRole);

        return existRole;
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        SystemRole existRole = getSystemRoleById(id);
        existRole.setDataStatus(status == 1 ? 1 : 0);
        this.baseMapper.updateById(existRole);
        return true;
    }

    @Override
    public Boolean deleteRole(String ids) {
        if (ids == null) {
            return true;
        }
        List<Long> idList = new ArrayList<>();
        if (ids.contains(",")) {
            String[] splitArray = ids.split(",");
            for (String str : splitArray) {
                idList.add(Long.parseLong(str));
            }
        } else {
            idList.add(Long.parseLong(ids));
        }
        this.baseMapper.deleteBatchIds(idList);
        return true;
    }

    @Override
    public Boolean bindingRole(RoleResourceDTO dto) {
        if (Objects.isNull(dto) || Objects.isNull(dto.getRoleId()) || Objects.isNull(dto.getResourceIds())) {
            throw new BusinessException(ExceptionDef.ERROR_COMMON_PARAM_NULL);
        }

        SystemRole systemRole = getSystemRoleById(dto.getRoleId());
        if (!DataDictionaryEnum.ENABLE.getCode().equals(systemRole.getDataStatus())) {
            throw new BusinessException("角色已被作废，请核实后再操作");
        }

        // 先删除角色-资源关联关系
        roleResourceService.deleteByRoleId(dto.getRoleId());

        // 再重新新增角色-资源关联关系
        List<SystemRoleResource> rrList = new ArrayList<>();
        dto.getResourceIds().forEach(e -> {
            SystemRoleResource roleResource = new SystemRoleResource();
            roleResource.setRoleId(dto.getRoleId());
            roleResource.setResourceId(e);
            rrList.add(roleResource);
        });

        roleResourceService.saveBatch(rrList);
        return true;
    }

    @Override
    public List<Long> findResourceByRole(Long roleId) {
        return roleResourceService.selectResourceByRoleId(roleId);
    }

    @Override
    public Page<User> findUsersByRole(SystemRoleQueryParam queryParam) {
        Page<UserRole> userRolePage = userRoleService.selectByRoleId(queryParam);
        List<UserRole> userRoleList = userRolePage.getRecords();
        List<Long> userIdList = userRoleList.stream().map(UserRole::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(userIdList)) {
            return PageUtils.getEmptyPage();
        }
        List<User> userList = userService.listByIds(userIdList);
        // 构建返回结果对象
        Page<User> result = new Page<>();
        result.setRecords(userList);
        result.setTotal(userRolePage.getTotal());
        result.setSize(userRolePage.getSize());
        result.setCurrent(userRolePage.getCurrent());
        result.setPages(userRolePage.getPages());
        return result;
    }
}
